<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import {
  getLogFiles,
  deleteFiles,
  addCheckProblems,
  getPalyFileApi,
  AddFileBrowseApi,
  CheckedProblem,
  GetFileDepTreesApi
} from '@/api/table'

import { Dialog } from '@/components/Dialog'
import { ref, unref, reactive, watch } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { Form, FormSchema } from '@/components/Form'
import { BaseButton } from '@/components/Button'
import { ElMessage, ElMessageBox, ElDivider, ElInput, ElTooltip, ElTree } from 'element-plus'
import { useValidator } from '@/hooks/web/useValidator'
import { getProblemTypesApi } from '@/api/role'
import { useForm } from '@/hooks/web/useForm'
import { useButtonPermiss } from '@/utils/buttonpermiss'
import { searchSchema, rowStyleFC, handleParams } from './util'
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()
const { t } = useI18n()

const { required } = useValidator()
const { formRegister, formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods
const columns: TableColumn[] = [
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  // {
  //   field: 'workTypeName',
  //   label: '作业类型',
  //   sortable: true
  //   // slots: {
  //   //   default: ({ row }: any) => {
  //   //     const workTypeColor = row.workTypeColor || '#000'
  //   //     const style = { color: workTypeColor }
  //   //     return (
  //   //       <>{workTypeColor ? <span style={style}>{row.workTypeName}</span> : row.workTypeName}</>
  //   //     )
  //   //   }
  //   // }
  // },
  {
    field: 'fileName',
    label: t('common.fileName'),
    sortable: true
  },
  {
    field: 'stationName',
    label: '采集站',
    sortable: true
  },
  {
    field: 'depName',
    label: '部门',
    sortable: true
  },

  {
    field: 'userName',
    label: '用户',
    sortable: true
  },
  {
    field: 'deviceNo',
    label: '设备编号',
    sortable: true
  },
  {
    field: 'fileTime',
    label: '拍摄时间',
    sortable: true
  },
  {
    field: 'collectTime',
    label: '采集时间',
    sortable: true
  },
  {
    field: 'uploadFileTime',
    label: '上传时间',
    sortable: true
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    align: 'center',
    fixed: 'right',
    width: 240,
    slots: {
      default: (data: any) => {
        return (
          <>
            <BaseButton type="primary" onClick={() => look(data.row)}>
              {t('exampleDemo.detail')}
            </BaseButton>
            {haspermiss.value.includes('删除') ? (
              <BaseButton type="danger" onClick={() => delData(data.row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            ) : null}
          </>
        )
      }
    }
  }
]
let currentRow = ref<files | null>(null)
interface files {
  guid: string
  filePath: string
  fileName: string
}
const showVideoLoading = ref(false)
const showDetail = ref(false)
let textV = ref()
const textUrl = ref()
let isHaveFile = ref(false)
const look = async (row) => {
  showDetail.value = true
  showVideoLoading.value = true
  currentRow.value = row
  AddFileBrowseApi({ fileGuid: row.guid })
  const res = await CheckedProblem({ fileGuid: row.guid })
  console.log('CheckedProblem-----------', !res)
  isHaveFile.value = !res
  getPalyFileApi({ fileGuid: row.guid })
    .then((res) => {
      // const myBlob = new Blob([res.data], { type: 'text/plain' })
      // textUrl.value = URL.createObjectURL(myBlob)
      textUrl.value = res.data
      if (res.data) {
        fetch(res.data)
          .then((response) => response.text())
          .then((data) => {
            textV.value = data
            showVideoLoading.value = false
          })
          .catch((error) => {
            console.log('----------------', error)
            showVideoLoading.value = false
            ElMessage({
              message: '日志加载失败',
              type: 'error'
            })
          })
      }
    })
    .catch(() => {
      showVideoLoading.value = false
      ElMessage({
        message: '日志加载失败',
        type: 'warning'
      })
    })
}
const delLoading = ref(false)
const ids = ref<string[]>([])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getLogFiles({
      pageNo: unref(currentPage),
      pageRow: unref(pageSize),
      pageModel: { ...unref(searchParams) }
    })
    let list = res.data.pageModels
    list.map((item) => {
      item.filePath1 = item.filePath
    })
    return {
      list: res.data.pageModels || [],
      total: res.data.totalCount || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteFiles(unref(ids))
    return !!res
  }
})

const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = handleParams(params)
  getList()
}
// const searchSchema = reactive<FormSchema[]>([
//   {
//     field: 'depName',
//     label: '部门',
//     component: 'Input'
//   },
//   {
//     field: 'userName',
//     label: '用户',
//     component: 'Input'
//   },
//   {
//     field: 'deviceNo',
//     label: '设备编号',
//     component: 'Input'
//   },
//   {
//     field: 'fileName',
//     label: t('common.fileName'),
//     component: 'Input'
//   },
//   {
//     field: 'date',
//     label: '拍摄时间',
//     component: 'DatePicker',
//     componentProps: {
//       style: { width: '340px' },
//       type: 'datetimerange',
//       valueFormat: 'YYYY-MM-DD HH:mm:ss',
//       StartPlaceholder: 'Start date',
//       EndPlaceholder: 'End date'
//     }
//   }
// ])
const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.guid] : elTableExpose?.getSelectionRows().map((v) => v.guid) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

interface ProblemType {
  label: string
  value: string
}

const typelist = ref<ProblemType[]>([])

const getTypeList = async () => {
  let res = await getProblemTypesApi({})
  if (res.data) {
    res.data.map((item) => {
      typelist.value.push({
        label: item.typeName,
        value: item.guid
      })
    })
  }
}

getTypeList()
const formSchema = ref<FormSchema[]>([
  {
    field: 'problemType',
    label: t('problem.problemType'),
    component: 'Select',
    componentProps: {
      clearable: true,
      placeholder: '请选择问题类型'
    },
    optionApi: async () => {
      return typelist.value
    }
  },
  {
    field: 'problemContent',
    label: t('problem.problemContent'),
    component: 'Input',
    componentProps: {
      type: 'textarea',
      inputStyle: { height: '180px' }
    }
  },
  {
    field: 'remark',
    label: t('common.remark'),
    component: 'Input',
    componentProps: {
      type: 'textarea',
      inputStyle: { height: '120px' }
    }
  }
])

const rules = reactive({
  problemType: [required()],
  problemContent: [required()]
})
let saveLoading = ref(false)
const save = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    console.log(formData, currentRow)
    if (formData) {
      formData.fileGuid = currentRow.value?.guid
      saveLoading.value = true
      let res = await addCheckProblems(formData).finally(() => {
        saveLoading.value = false
      })

      if (res) {
        showDetail.value = false
      }
    }
  }
}

const data = ref([])
const GetFileDepTreesApiData = async (deviceNo = '') => {
  const res = await GetFileDepTreesApi({ deviceNo })
  // console.log('GetFileDepTreesApi', res)
  let treeData = res.data || []
  treeData.map((item: any) => {
    item.depGuid = item.guid
    if (item.children) {
      item.children.map((child: any) => {
        child.depGuid = item.guid
        child.deviceGuid = child.guid
        if (child.children) {
          child.children.map((nchild: any) => {
            nchild.depGuid = item.guid
            nchild.deviceGuid = child.guid
            nchild.time = nchild.name
          })
        }
      })
    }
  })
  console.log('GetFileDepTreesApi', treeData)
  data.value = treeData
  return treeData
}
GetFileDepTreesApiData()
interface Tree {
  label: string
  children?: Tree[]
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const handleNodeClick = (node, data: Tree, tree) => {
  console.log(data)
  const { depGuid, time, deviceGuid } = data.data
  if (time) {
    searchParams.value = {
      depGuid,
      deviceGuid,
      startTime: time + ' 00:00:00',
      endTime: time + ' 23:59:59'
    }
  }

  getList()
}
watch(filterText, (val) => {
  // treeRef.value!.filter(val)
  GetFileDepTreesApiData(val)
})

const defaultProps = {
  children: 'children',
  label: 'name'
}
</script>

<template>
  <ContentWrap>
    <div class="flex justify-between">
      <div class="left">
        <el-input
          v-model="filterText"
          style="width: 240px"
          placeholder="输入设备号进行过滤"
          clearable
        />
        <el-tree
          ref="treeRef"
          style="max-width: 600px"
          :data="data"
          :props="defaultProps"
          @node-click="handleNodeClick"
        />
      </div>
      <div class="right">
        <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
        <Table
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :reserveIndex="true"
          :columns="columns"
          :data="dataList"
          :loading="loading"
          :pagination="{
            total
          }"
          @register="tableRegister"
          :rowStyle="rowStyleFC"
        />
      </div>
    </div>
    <Dialog v-model="showDetail" title="详情">
      <div class="row_d" v-if="!isHaveFile">
        <div style="flex: 1; height: 400px; overflow-y: scroll" v-loading="showVideoLoading">{{
          textV
        }}</div>
        <div class="rombox">
          <Form
            :rules="rules"
            @register="formRegister"
            :schema="formSchema"
            :isCol="false"
            ref="writeRef"
          />
        </div>
      </div>
      <div v-else class="row_d">
        <div style="flex: 1; height: 400px; overflow-y: scroll" v-loading="showVideoLoading">{{
          textV
        }}</div>
      </div>
      <template #footer>
        <!-- <a class="downstyle" :href="textUrl" download="日志.log">下载源文件</a> -->
        <BaseButton type="primary" :loading="saveLoading" @click="save" v-if="!isHaveFile">
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="showDetail = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </ContentWrap>
</template>
<style scoped>
.row_d {
  display: flex;
  /* align-items: center; */
}
.rombox {
  flex: 2;
  margin-left: 20px;
}
.downstyle {
  margin-right: 20px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  line-height: 1;
  height: 32px;
  white-space: nowrap;
  cursor: pointer;
  color: #fff;
  text-align: center;
  box-sizing: border-box;
  outline: 0;
  transition: 0.1s;
  font-weight: 500;
  -webkit-user-select: none;
  user-select: none;
  vertical-align: middle;
  -webkit-appearance: none;
  background-color: #529b2e;
  border: var(--el-border);
  border-color: #529b2e;
  padding: 8px 15px;
  font-size: 14px;
  border-radius: 4px;
  text-decoration: none;
}
.left {
  width: 280px;
  border-right: 1px dashed #ccc;
  margin-right: 10px;
}
</style>
